package com.zyb.patient.activity;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.widget.TextView;

import com.zyb.patient.R;
import com.zyb.patient.view.AboutProgressWebView;

public class WebViewActivity extends BaseActivity implements OnClickListener {
	
	private static final String TAG = "WebViewActivity";
	private static final String APP_CACAHE_DIRNAME = "/webcache";
	private String title, url;
	
	private AboutProgressWebView webView;
	private View mErrorView;
	private View back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_webview_content);
		initViews();
		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initViews() {

		Intent it = getIntent();
		title = it.getStringExtra("title");
		url = it.getStringExtra("url");

		if (TextUtils.isEmpty(url) || TextUtils.isEmpty(title)) {
			showToast("参数异常");
			// return;
		}

		TextView titleView = (TextView) findViewById(R.id.head_layout_tv);
		titleView.setText(title);

		// back = findViewById(R.id.head_layout_back);
		// back.setOnClickListener(this);

		webView = (AboutProgressWebView) findViewById(R.id.web);
		webView.setTitleView(titleView, title);

		mErrorView = findViewById(R.id.fail_layout);
		webView.setErrorView(mErrorView);
		// webView.setTitleView(mTextView);
		WebSettings wSet = webView.getSettings();
		wSet.setJavaScriptEnabled(true);
		webView.addJavascriptInterface(this, "jo");
		wSet.setRenderPriority(RenderPriority.HIGH);
		wSet.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置 缓存模式
		// 开启 DOM storage API 功能
		wSet.setDomStorageEnabled(true);
		// 开启 database storage API 功能
		wSet.setDatabaseEnabled(true);
		String cacheDirPath = getFilesDir().getAbsolutePath()
				+ APP_CACAHE_DIRNAME;
		// String cacheDirPath =
		// getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
		// 设置数据库缓存路径
		wSet.setDatabasePath(cacheDirPath);
		// 设置 Application Caches 缓存目录
		wSet.setAppCachePath(cacheDirPath);
		// 开启 Application Caches 功能
		wSet.setAppCacheEnabled(true);
		webView.setDownloadListener(new DownloadListener() {
			@Override
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype,
					long contentLength) {
				if (url != null && url.startsWith("http://"))
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			}
		});
		/*** 支持 flash ***/
		String temp = "<html><body bgcolor=\"" + "black"
				+ "\"> <br/><embed src=\"" + url + "\" width=\"" + "100%"
				+ "\" height=\"" + "90%" + "\" scale=\"" + "noscale"
				+ "\" type=\"" + "application/x-shockwave-flash"
				+ "\"> </embed></body></html>";
		String mimeType = "text/html";
		String encoding = "utf-8";
		webView.loadDataWithBaseURL("null", temp, mimeType, encoding, "");

		webView.loadUrl(url);
		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	public void showDialog(String title, String content) {
		// DialogCommon dialog = new DialogCommon(this);
		// dialog.setTitle(title);
		// dialog.setContent(content);
		// dialog.setCancelable(false);
		// dialog.setOkOnClick(new OnClickListener() {
		// 
		// @Override
		// public void onClick(View v) {
		// DialogCommon dialog = (DialogCommon) v.getTag();
		// dialog.dismiss();
		// }
		// });
		// dialog.setCancleGone();
		// dialog.show();
	}

	@Override
	public void onClick(View v) {
		if (v == back) {
			onBackPressed();
		}
	}

	@Override
	public void onBackPressed() {
		Log.e("onBackPressed", webView.canGoBack() + "");
		if (webView.canGoBack()) {
			webView.goBack();
		} else {
			finish();
		}
	}

	/**
	 * 清除WebView缓存
	 */
	public void clearWebViewCache() {

		// 清理Webview缓存数据库
		try {
			deleteDatabase("webview.db");
			deleteDatabase("webviewCache.db");
		} catch (Exception e) {
			e.printStackTrace();
		}

		// WebView 缓存文件
		File appCacheDir = new File(getFilesDir().getAbsolutePath()
				+ APP_CACAHE_DIRNAME);
		Log.e(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());

		File webviewCacheDir = new File(getCacheDir().getAbsolutePath()
				+ "/webviewCache");
		Log.e(TAG, "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

		// 删除webview 缓存目录
		if (webviewCacheDir.exists()) {
			deleteFile(webviewCacheDir);
		}
		// 删除webview 缓存 缓存目录
		if (appCacheDir.exists()) {
			deleteFile(appCacheDir);
		}
	}

	/**
	 * 递归删除 文件/文件夹
	 * 
	 * @param file
	 */
	public void deleteFile(File file) {

		Log.i(TAG, "delete file path=" + file.getAbsolutePath());

		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
		}
	}
}
